package so.shanku.essential.activity;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.IGetServicesDataCallBack;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/8.
 */
public class UserChangePasswordActivity extends BaseUIActivity {
    /**
     * 1.手机验证
     */
    @ViewInject(id = R.id.tv_confirm_phone)
    private TextView tv_confirm_phone;
    /**
     * 2.密码验证
     */
    @ViewInject(id = R.id.tv_confirm_password)
    private TextView tv_confirm_password;
    /**
     * 输入框的隐藏（手机验证）
     */
    @ViewInject(id = R.id.linearlayout_confirm_phone)
    private LinearLayout linearlayout_confirm_phone;
    /**
     * 输入手机号
     */
    @ViewInject(id = R.id.et_input_phone)
    private EditText et_input_phone;
    /**
     * 输入验证码
     */
    @ViewInject(id = R.id.et_input_password)
    private EditText et_input_password;
    /**
     * 发送验证码
     */
    @ViewInject(id = R.id.btn_send_code, click = "sendpassword_click")
    private TextView tv_sendpassword;
    /**
     * 输入框的隐藏（确认密码）
     */
    @ViewInject(id = R.id.linearlayout_confirm_password)
    private LinearLayout linearlayout_confirm_password;
    /**
     * 新密码
     */
    @ViewInject(id = R.id.et_new_password)
    private EditText et_new_password;
    /**
     * 确认密码
     */
    @ViewInject(id = R.id.et_confirm_password)
    private EditText et_confirm_password;
    /**
     * 下一步
     */
    @ViewInject(id = R.id.bt_confirm, click = "bt_confirm_click")
    private TextView bt_confirm;
    private boolean isFirst;
    /**
     * 定时器
     */
    private TimeCount time;
    private String passWord;
    private String confirmPassWord;
    private boolean isSend;//用来防止网络延时后发送验证码

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_password);
        setCenter_title(R.string.change_password);
        isFirst = true;
        isSend = false;
        sendCodeClick();
        time = new TimeCount(120000, 1000);

    }

    public void bt_confirm_click(View view) {
        if (isFirst) {
            if (nextStepJudge()) {
                getData_UserSubmitCode();
            }

        } else {
            if (confirmChangeJudge()) {
                getData_ConfirmChange();
            }
        }

    }

    //当getData_UserSubmitCode成功后调用
    public void getData_UserSubmitCode_Success() {
        linearlayout_confirm_phone.setVisibility(View.GONE);
        tv_confirm_password.setBackgroundResource(R.drawable.confirm_password);
        tv_confirm_phone.setBackgroundResource(R.color.white);
        linearlayout_confirm_password.setVisibility(View.VISIBLE);
        bt_confirm.setText(R.string.confirm_change);
        isFirst = false;
    }

    //当 getData_ConfirmChange成功后调用
    public void getData_ConfirmChange_Success() {
        linearlayout_confirm_phone.setVisibility(View.VISIBLE);
        tv_confirm_phone.setBackgroundResource(R.drawable.confirm_phone);
        tv_confirm_password.setBackgroundResource(R.color.white);
        linearlayout_confirm_password.setVisibility(View.GONE);
        bt_confirm.setText(R.string.next);
        isFirst = true;
    }

    /**
     * 判断手机号码
     */
    private String userPhone;

    public boolean judgeMobileNo() {
        userPhone = et_input_phone.getText().toString();
        if (TextUtils.isEmpty(userPhone)) {
            //手机号码为空的情况
            toast.showToast(R.string.register_name_null);
            return false;
        } else if (!StringUtil.isMobileNO(userPhone)) {
            toast.showToast(R.string.phone_formal_error);
            return false;
        }
        return true;
    }


    /**
     * 发送验证码获取数据
     */
    private void getData_UserSendCode() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", Utils.getUserAccount(UserChangePasswordActivity.this));
        params.put("phone", userPhone);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_SendMessagePasswrod);
        queue.setWhat(GetDataConfing.what_SendMessagePasswrod);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 下一步获取数据（提交验证码）
     */
    public void getData_UserSubmitCode() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", Utils.getUserAccount(UserChangePasswordActivity.this));
        params.put("phone", userPhone);
        params.put("code", getCode);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_SubmitPassWrod);
        queue.setWhat(GetDataConfing.what_SubmitPassWrod);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 确认修改
     */
    public void getData_ConfirmChange() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", Utils.getUserAccount(UserChangePasswordActivity.this));
        params.put("passWrod", passWord);
        params.put("xinpassWrod", passWord);
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_UpdateUserPassword);
        queue.setWhat(GetDataConfing.what_UpdateUserPassword);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 获取服务器数据的返回信息
     */
    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(UserChangePasswordActivity.this,
                        entity.getInfo())) {
                    if (entity.what == GetDataConfing.what_SendMessagePasswrod) {
                        time.start();
                        tv_sendpassword.setEnabled(false);
                    } else if (entity.what == GetDataConfing.what_SubmitPassWrod) {
                        getData_UserSubmitCode_Success();
                    } else if (entity.what == GetDataConfing.what_UpdateUserPassword) {
                        toast.showToast(R.string.change_success);
                        getData_ConfirmChange_Success();
                        UserChangePasswordActivity.this.finish();
                    }
                }
            } else {
                ShowGetDataError.showNetError(UserChangePasswordActivity.this);
            }
            loadingToast.dismiss();
        }
    };

    /**
     * 点击发送验证码（防止网络延时发送多条验证码）
     */
    public void sendCodeClick() {
        tv_sendpassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (judgeMobileNo()) {
                    isSend = true;
                    getData_UserSendCode();
                }
            }
        });
    }

    private String getCode;

    //验证码倒计时
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            //参数依次为总时长,和计时的时间间隔
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            //计时完毕时触发
            tv_sendpassword.setText(getString(R.string.revalidation));
            tv_sendpassword.setClickable(true);
            tv_sendpassword.setEnabled(true);
            getCode = "";
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            tv_sendpassword.setText(millisUntilFinished / 1000 + getString(R.string.second));
        }
    }

    /**
     * 点击下一步的判断
     */
    public boolean nextStepJudge() {
        boolean isjudge = true;
        boolean captcha = true;
        getCode = et_input_password.getText().toString();
        if (getCode == null || "".equals(getCode)) {
            toast.showToast(R.string.pls_input_code);
            captcha = false;
        }
        isjudge = judgeMobileNo() && captcha;
        return isjudge;
    }

    /**
     * 确认修改的判断
     */
    public boolean confirmChangeJudge() {
        boolean isjudge = true;
        boolean captcha = true;

        passWord = et_new_password.getText().toString();
        confirmPassWord = et_confirm_password.getText().toString();
        if (TextUtils.isEmpty(confirmPassWord)) {
            toast.showToast(R.string.pls_input_confirm_pw);
            captcha = false;
        } else {
            if (!confirmPassWord.equals(passWord)) {
                toast.showToast(R.string.password_differ);
                captcha = false;
            }

        }
        isjudge = isPasswordAuthentication(passWord) && captcha;
        return isjudge;
    }

    /**
     * 密码判断
     */
    public boolean isPasswordAuthentication(String password) {
        if (!StringUtil.passwordAuthenticationLength(password)) {
            toast.showToast(R.string.register_passwordRule);
            return false;
        } else if (!StringUtil.passwordAuthentication(password)) {
            toast.showToast(R.string.password_format_error);
            return false;
        }
        return true;
    }
}
